package com.motionlog.activity;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.FilterQueryProvider;
import android.widget.ListView;

import com.motionlog.R;
import com.motionlog.adapter.HistoryCursorAdapter;
import com.motionlog.model.Database;

public class MotionOrganize extends Activity {

	protected static final String TAG = MotionOrganize.class.getSimpleName();

	DatePicker mDatePicker;
	ListView mListView;
	// List<Log> mLogItems;
	// HistoryAdapter mAdapter;
	HistoryCursorAdapter mAdapter;

	Database mDb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.motion_organize);

		mDatePicker = (DatePicker) findViewById(R.id.date_picker);
		mListView = (ListView) findViewById(R.id.list);

		// mLogItems = new ArrayList<Log>();
		// mAdapter = new HistoryAdapter(this, mLogItems);
		mDb = Database.getInstance(this);

		mDatePicker.getYear();
		mDatePicker.getMonth();
		mDatePicker.getDayOfMonth();
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		final Cursor c = mDb.selectLog(new Date());
		mAdapter = new HistoryCursorAdapter(this, c);
		mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
			@Override
			public Cursor runQuery(CharSequence constraint) {
				return null;
			}
		});
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(MotionOrganize.this, HistoryItem.class);
				android.util.Log.d(TAG, "id: " + id);
				i.putExtra("logId", id);
				startActivity(i);
			}
		});

		mDatePicker.init(year, month, day,
				new DatePicker.OnDateChangedListener() {
					@Override
					public void onDateChanged(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						int y = view.getYear();
						int m = view.getMonth();
						int d = view.getDayOfMonth();
						android.util.Log.d(TAG, "date: "
								+ new Date(y - 1900, m, d).toString() + ", y: "
								+ y + ", m: " + m);
						Cursor cursor = mDb.selectLog(new Date(y - 1900, m, d));
						mAdapter.changeCursor(cursor);
						mAdapter.notifyDataSetChanged();
					}
				});
	}
}
